import request from '@/chaos/functions/request';
import type { ParamsType, PageParamsType } from '@/chaos/functions/dataType';
import { message } from 'antd';
import { exportExcel } from '@/chaos/functions/execl';

export async function add(domain: string, param: ParamsType = {}) {
  message.loading('正在添加');
  const { data } = await request(`/manage/${domain}/add`, { data: param });
  if (data) {
    message.success('添加成功');
  }
  return data || false;
}

export async function update(domain: string, mu: string, param: ParamsType = {}) {
  message.loading('正在更新');
  const { data } = await request(`/manage/${domain}/update`, { data: { mu, data: param } });
  if (data) {
    message.success('更新成功');
  }
  return data || false;
}

export async function remove(domain: string, mu: string) {
  message.loading('正在删除');
  const { data } = await request(`/manage/${domain}/delete`, { data: { mu } });
  if (data) {
    message.success('删除成功');
  }
  return data || false;
}

export async function page(domain: string, params: PageParamsType) {
  const { current: pageNum, pageSize, data: param } = params;
  const { page: pageData } = await request(`/manage/${domain}/page`, {
    data: { pageNum, pageSize, data: param },
  });
  const { list: listData, current, total } = pageData;
  return listData ? { list: listData, total, current } : { list: [], total: 0, current };
}

export async function list(domain: string, param: ParamsType = {}) {
  const { data } = await request(`/manage/${domain}/list`, { data: param });
  return data || [];
}

export async function one(domain: string, mu: string) {
  const { data } = await request(`/manage/${domain}/one`, { data: { mu } });
  return data || {};
}

export async function submit(method: string, param: ParamsType = {}) {
  const { data } = await request(`/manage/${method}`, { data: param });
  return data || false;
}

export async function search(method: string, params: PageParamsType) {
  const { current: pageNum, pageSize, data: param } = params;
  const { page: pageData } = await request(`/manage/${method}`, {
    data: { pageNum, pageSize, data: param },
  });
  const { list: listData, current, total } = pageData;
  return listData ? { list: listData, total, current } : { list: [], total: 0, current };
}

export async function query(method: string, param: ParamsType) {
  const { data } = await request(`/manage/${method}`, { data: param });
  return data || {};
}

export async function searchExport(
  method: string,
  header: any,
  filename: string = 'demo',
  data: ParamsType,
) {
  let pageNum = 1;
  let res;
  do {
    /* eslint-disable no-await-in-loop */
    res = await request(`/manage/${method}`, { data: { pageNum, pageSize: 1000, data } });
    if (res.page.list) {
      exportExcel(header, res.page.list, filename.concat('.xlsx'));
      pageNum += 1;
    }
  } while (res.page.list);
  return true;
}
